package com.ledi.guns.modular.ledipay.service.impl;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ledi.guns.common.exception.AppCheckException;
import com.ledi.guns.common.persistence.dao.AgentInfoMapper;
import com.ledi.guns.common.persistence.dao.BillDetailMapper;
import com.ledi.guns.common.persistence.dao.RoleMapper;
import com.ledi.guns.common.persistence.dao.SchoolInfoMapper;
import com.ledi.guns.common.persistence.dao.UserMapper;
import com.ledi.guns.common.persistence.model.SchoolInfo;
import com.ledi.guns.common.persistence.model.TAgentInfo;
import com.ledi.guns.common.persistence.model.User;
import com.ledi.guns.common.persistence.model.vo.AgentCountDataVo;
import com.ledi.guns.common.persistence.model.vo.AgentInfoVo;
import com.ledi.guns.common.persistence.model.vo.AgentNamesVo;
import com.ledi.guns.common.persistence.model.vo.AgentStatisticalDataVo;
import com.ledi.guns.common.persistence.model.vo.AgentUserVo;
import com.ledi.guns.common.persistence.model.vo.HotAgentVo;
import com.ledi.guns.common.persistence.model.vo.SeeAgentInfoVo;
import com.ledi.guns.common.util.StringUtil;
import com.ledi.guns.core.redis.KeyValueDAO;
import com.ledi.guns.core.shiro.ShiroKit;
import com.ledi.guns.core.shiro.ShiroUser;
import com.ledi.guns.core.util.DateUtil;
import com.ledi.guns.core.util.SystemConstans;
import com.ledi.guns.modular.ledipay.controller.req.agent.AddAgentInfo;
import com.ledi.guns.modular.ledipay.controller.req.agent.AddAgentUser;
import com.ledi.guns.modular.ledipay.controller.req.agent.EditAgentInfo;
import com.ledi.guns.modular.ledipay.controller.req.agent.QueryAgentCountData;
import com.ledi.guns.modular.ledipay.controller.req.agent.QueryAgentId;
import com.ledi.guns.modular.ledipay.controller.req.agent.QueryAgentInfo;
import com.ledi.guns.modular.ledipay.controller.req.agent.QueryAgentNames;
import com.ledi.guns.modular.ledipay.controller.req.agent.QuerySeeAgentInfo;

/**
 * 代理商后台Service
 *
 * @author fengshuonan
 * @Date 2017-11-29 10:53:00
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AgentServiceImpl extends ServiceImpl<AgentInfoMapper, TAgentInfo> {

	@Resource
	private AgentInfoMapper agentInfoMapper;
	@Resource
	private UserMapper userMapper;
	@Resource
	private SchoolInfoMapper schoolInfoMapper;
	@Resource
	private BillDetailMapper billDetailMapper;
	@Resource
	private RoleMapper roleMapper;
	@Resource
	private KeyValueDAO keyValueDAO;

	public Page<AgentInfoVo> getAgentInfoList(Page<AgentInfoVo> page, QueryAgentInfo queryAgentInfo) {

		List<AgentInfoVo> searchResult = agentInfoMapper.getAgentInfo(page, queryAgentInfo.getSearch());
		Optional.ofNullable(searchResult)
		.map(searchResults -> {
			searchResults.forEach(agentInfoVo -> {
				Optional.ofNullable(agentInfoVo.getTurnover())
				.orElseGet(() -> {
					agentInfoVo.setTurnover(new BigDecimal("0"));
					return agentInfoVo.getTurnover();
				});
				Optional.ofNullable(agentInfoVo)
				.filter(agentInfo -> agentInfoVo.getSchoolCount() == 0)
				.map(agentInfo -> {
					agentInfoVo.setIsDeleteStatus(1);
					return agentInfo;
				})
				.orElseGet(() -> {
					agentInfoVo.setIsDeleteStatus(0);
					return agentInfoVo;
				});

				Map<String, Object> param = new HashMap<String, Object>();
				param.put("agentId", agentInfoVo.getId());
				AgentStatisticalDataVo count = billDetailMapper.findCountByParam(param);
				if (count != null) {
					agentInfoVo.setFlow(count.getFlow());
					agentInfoVo.setAliFlow(count.getAliFlow());
				}

			});
			return searchResult;
		})
		.orElseThrow(() -> new AppCheckException("agent.searchAgentInfoError.code",
				"agent.searchAgentInfoError.message"));
		page.setRecords(searchResult);
		return page;
	}

	public void addAgentInfo(AddAgentInfo addAgentInfo) {

		ShiroUser currentUser = ShiroKit.getUser();
		List<TAgentInfo> agentInfoList = agentInfoMapper.selectList(new EntityWrapper<TAgentInfo>()
				.eq("is_delete", 0));
		// 校验代理商区域
		checkAgentNameAndArea(agentInfoList, addAgentInfo.getAgentName(), addAgentInfo.getArea());
		// 校验当前用户是否被删除
		User oneUser = userMapper.selectById(currentUser.getId());
		if (1 != oneUser.getStatus()) {
			throw new AppCheckException("agent.agentUserHaveDelete.code", "agent.agentUserHaveDelete.message");
		}
		// 校验密码是否包含中文字符
		String agentPasswd = addAgentInfo.getLoginPasswd();
		for (int i = 0; i < agentPasswd.length(); i++) {
			if (StringUtil.isChinese(agentPasswd.charAt(i))) {
				throw new AppCheckException("agent.passwdContainChinese.code", "agent.passwdContainChinese.message");
			}
		}
		Integer creatorId = currentUser.getId();
		List<String> roleNames = currentUser.getRoleNames();
		String roles = roleNames.stream().collect(Collectors.joining(","));
		Map<String, Object> agentInfoMap = new HashMap<>();
		agentInfoMap.put("contact_tel", addAgentInfo.getContactTel());
		List<TAgentInfo> agentInfos = agentInfoMapper.selectByMap(agentInfoMap);
		if (null != agentInfos && agentInfos.size() > 0) {
			agentInfos.forEach(oneAgent -> {
				if (1 == oneAgent.getIsDelete()) {
					oneAgent.setIsDelete(0);
					oneAgent.setCreateTime(new Date());
					oneAgent.setCreatorId(currentUser.getId().longValue());
					oneAgent.setCreatorRole(roles);
					BeanUtils.copyProperties(addAgentInfo, oneAgent);
					Integer updateAgentInfo = agentInfoMapper.updateById(oneAgent);
					if (updateAgentInfo < 1) {
						throw new AppCheckException("agent.addAgentError.code", "agent.addAgentError.message");
					}
				}
			});
		} else {
			TAgentInfo agentInfo = new TAgentInfo();
			agentInfo.setCreatorId(creatorId.longValue());
			agentInfo.setCreatorRole(roles);
			agentInfo.setCreateTime(new Date());
			agentInfo.setIsDelete(0);
			BeanUtils.copyProperties(addAgentInfo, agentInfo);
			Integer insert = agentInfoMapper.insert(agentInfo);
			if (insert < 1) {
				throw new AppCheckException("agent.addAgentError.code", "agent.addAgentError.message");
			}
		}
		// 增加代理商用户
		Map<String, Object> agentMap = new HashMap<>();
		agentMap.put("contact_tel", addAgentInfo.getContactTel());
		List<TAgentInfo> agentInfoByMap = agentInfoMapper.selectByMap(agentMap);
		if (null != agentInfoByMap && agentInfoByMap.size() > 0) {
			agentInfoByMap.forEach(oneAgent -> {
				int roleId = roleMapper.getIdByName(SystemConstans.A_ROLENAME);
				Map<String, Object> agentUserMap = new HashMap<>();
				agentUserMap.put("account", addAgentInfo.getContactTel());
				List<User> agentUserList = userMapper.selectByMap(agentUserMap);
				if (null != agentUserList && agentUserList.size() > 0) {
					agentUserList.forEach(agentUser -> {
						if (1 == agentUser.getStatus()) {
							String agentRoleIds = agentUser.getRoleid();
							List<String> agentRoleIdList = Arrays.asList(agentRoleIds.split(","));
							agentRoleIdList.forEach(agentRoleid -> {
								if (String.valueOf(roleId).equals(agentRoleid)) {
									throw new AppCheckException("staff.userHaveExistError.code",
											"staff.userHaveExistError.message");
								}
								int staffId = roleMapper.getIdByName(SystemConstans.P_ROLNAME);
								if (String.valueOf(staffId).equals(agentRoleid)) {
									throw new AppCheckException("staff.userHaveExistError.code",
											"staff.userHaveExistError.message");
								}
								// int schoolId = roleMapper.getIdByName(SystemConstans.K_ROLENAME);
								// if (String.valueOf(schoolId).equals(agentRoleid)) {
								// throw new AppCheckException("staff.userHaveExistError.code",
								// "staff.userHaveExistError.message");
								// }
									int teacherId = roleMapper.getIdByName(SystemConstans.T_ROLENAME);
									if (String.valueOf(teacherId).equals(agentRoleid)) {
										throw new AppCheckException("staff.userHaveExistError.code",
												"staff.userHaveExistError.message");
									}
									int agentUserId = roleMapper.getIdByName(SystemConstans.AU_ROLENAME);
									if (String.valueOf(agentUserId).equals(agentRoleid)) {
										throw new AppCheckException("staff.userHaveExistError.code",
												"staff.userHaveExistError.message");
									}
								});
							agentUser.setRoleid(agentRoleIds + "," + String.valueOf(roleId));
						} else {
							agentUser.setRoleid(String.valueOf(roleId));
						}
						agentUser.setSalt(ShiroKit.getRandomSalt(5));
						agentUser.setPassword(ShiroKit.md5(addAgentInfo.getLoginPasswd(), agentUser.getSalt()));
						agentUser.setAgentId(oneAgent.getId());
						agentUser.setStatus(1);
						agentUser.setName(addAgentInfo.getContactPeople());
						agentUser.setPhone(addAgentInfo.getContactTel());
						Integer userUpdate = userMapper.updateById(agentUser);
						if (userUpdate < 1) {
							throw new AppCheckException("agent.addAgentUserError.code",
									"agent.addAgentUserError.message");
						}
					});
				} else {
					User user = new User();
					user.setRoleid(String.valueOf(roleId));
					user.setSalt(ShiroKit.getRandomSalt(5));
					user.setPassword(ShiroKit.md5(addAgentInfo.getLoginPasswd(), user.getSalt()));
					user.setAgentId(oneAgent.getId());
					user.setStatus(1);
					user.setAccount(addAgentInfo.getContactTel());
					user.setPhone(addAgentInfo.getContactTel());
					user.setName(addAgentInfo.getContactPeople());
					user.setCreatetime(new Date());
					user.setCreateid(creatorId);
					user.setDeptid(SystemConstans.DEPT_CUSTOMER_INT);
					Integer userInsert = userMapper.insert(user);
					if (userInsert < 1) {
						throw new AppCheckException("agent.addAgentUserError.code", "agent.addAgentUserError.message");
					}
				}
			});
		} else {
			throw new AppCheckException("agent.addAgentError.code", "agent.addAgentError.message");
		}
	}

	public SeeAgentInfoVo seeAgentInfo(QuerySeeAgentInfo querySeeAgentInfo) {

		ShiroUser currentUser = ShiroKit.getUser();
		User user1 = userMapper.selectById(currentUser.getId());
		if (1 != user1.getStatus()) {
			throw new AppCheckException("workOrder.delete.code",
					"workOrder.delete.message", new Object[] { "无法查看代理商" });
		}
		TAgentInfo agentInfo = agentInfoMapper.selectByAgentId(querySeeAgentInfo.getAgentId());
		Optional.ofNullable(agentInfo)
		.orElseThrow(
				() -> new AppCheckException("agent.seeAgentInfoError.code", "agent.seeAgentInfoError.message"));
		SeeAgentInfoVo seeAgentInfoVo = new SeeAgentInfoVo();
		BeanUtils.copyProperties(agentInfo, seeAgentInfoVo);
		return seeAgentInfoVo;
	}

	/**
	 * 校验代理商名称和区域
	 *
	 * @param agentList
	 * @param newAgentName
	 * @param newArea
	 */
	public void checkAgentNameAndArea(List<TAgentInfo> agentList, String newAgentName, String newArea) {

		agentList.forEach(agent -> {
			// 校验代理商区域
				String originArea = agent.getArea();
				if (newArea.equals(originArea)) {
					throw new AppCheckException("agent.agentRegionRepeatError.code",
							"agent.agentRegionRepeatError.message");
				}
			});
	}

	/**
	 * 方法描述: [编辑代理商或者园所合伙人.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月25日-下午5:30:21<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 * 
	 * @param editAgentInfo
	 *            void
	 */
	public void editAgentInfo(EditAgentInfo editAgentInfo) {

		ShiroUser currentUser = ShiroKit.getUser();

		List<TAgentInfo> totalAgentInfoList = agentInfoMapper
				.selectList(new EntityWrapper<TAgentInfo>().eq("is_delete", 0)
						.ne("id", editAgentInfo.getId()));
		Optional.ofNullable(totalAgentInfoList)
		.orElseThrow(() -> new AppCheckException("agent.searchAgentsInfoError.code",
				"agent.searchAgentsInfoError.message"));
		// 校验代理商名称和区域
		checkAgentNameAndArea(totalAgentInfoList, editAgentInfo.getAgentName(), editAgentInfo.getArea());
		// 校验当前用户是否被删除
		User oneUser = userMapper.selectById(currentUser.getId());
		if (1 != oneUser.getStatus()) {
			throw new AppCheckException("agent.agentUserHaveDelete.code", "agent.agentUserHaveDelete.message");
		}

		TAgentInfo agentInfo = agentInfoMapper.selectByAgentId(editAgentInfo.getId());
		// 园所合伙人
		if (agentInfo.getAgentType() == SystemConstans.TWO) {
			if (agentInfo.getSchoolCount() > editAgentInfo.getSchoolCountLimit()) {
				throw new AppCheckException("agent.editAgentInfoError.schoolCountGtLimit.code", "agent.editAgentInfoError.schoolCountGtLimit.message");
			}
		}
		BeanUtils.copyProperties(editAgentInfo, agentInfo);
		Integer creatorId = currentUser.getId();
		List<String> roleNames = currentUser.getRoleNames();
		String roles = roleNames.stream().collect(Collectors.joining(","));
		agentInfo.setUpdaterId(creatorId.longValue());
		agentInfo.setUpdaterRole(roles);
		agentInfo.setUpdateTime(new Date());
		agentInfo.setVersionNo(editAgentInfo.getVersionNo());
		Integer editAgentUpdate = agentInfoMapper.updateById(agentInfo);
		if (editAgentUpdate < 1) {
			throw new AppCheckException("agent.editAgentInfoError.code", "agent.editAgentInfoError.message");
		}
		Map<String, Object> agentUser = new HashMap<>();
		agentUser.put("account", editAgentInfo.getContactTel());
		agentUser.put("status", 1);
		List<User> agentUserList = userMapper.selectByMap(agentUser);
		if (null != agentUserList && agentUserList.size() > 0) {
			agentUserList.forEach(newAgentUser -> {
				newAgentUser.setName(editAgentInfo.getContactPeople());
				newAgentUser.setUpdatetime(new Date());
				newAgentUser.setUpdateid(creatorId);
				Integer newAgentUserUpdate = userMapper.updateById(newAgentUser);
				if (newAgentUserUpdate < 1) {
					throw new AppCheckException("agent.editAgentInfoError.code", "agent.editAgentInfoError.message");
				}
			});
		} else {
			throw new AppCheckException("agent.editAgentInfoError.code", "agent.editAgentInfoError.message");
		}
	}

	public void deleteAgentInfo(Integer id) {

		ShiroUser currentUser = ShiroKit.getUser();
		User user1 = userMapper.selectById(currentUser.getId());
		if (1 != user1.getStatus()) {
			throw new AppCheckException("workOrder.delete.code",
					"workOrder.delete.message", new Object[] { "无法删除代理商" });
		}
		// 校验是否能删除
		Map<String, Object> schoolMap = new HashMap<>();
		schoolMap.put("belong_agent", id);
		List<SchoolInfo> schoolInfoList = schoolInfoMapper.selectByMap(schoolMap);
		if (null != schoolInfoList && schoolInfoList.size() > 0) {
			throw new AppCheckException("agent.deleteAgentError.code", "agent.deleteAgentError.message");
		}

		TAgentInfo agentInfo = agentInfoMapper.selectById(id);
		Optional.ofNullable(agentInfo)
		.orElseThrow(
				() -> new AppCheckException("agent.searchUserError.code", "agent.searchUserError.message"));
		// 查询要删除的用户
		if (1 == agentInfo.getIsDelete()) {
			throw new AppCheckException("agent.agentUserHaveDeleteError.code",
					"agent.agentUserHaveDeleteError.message");
		}
		Integer creatorId = currentUser.getId();
		List<String> roleNames = currentUser.getRoleNames();
		String roles = roleNames.stream().collect(Collectors.joining(","));
		agentInfo.setUpdaterId(creatorId.longValue());
		agentInfo.setUpdaterRole(roles);
		agentInfo.setUpdateTime(new Date());
		agentInfo.setIsDelete(1);
		Integer editAgentUpdate = agentInfoMapper.updateById(agentInfo);
		if (editAgentUpdate < 1) {
			throw new AppCheckException("agent.editAgentInfoError.code", "agent.editAgentInfoError.message");
		}
		Map<String, Object> agentUser = new HashMap<>();
		agentUser.put("account", agentInfo.getContactTel());
		List<User> user = userMapper.selectByMap(agentUser);
		if (null != user && user.size() > 0) {
			user.forEach(oneUser -> {
				String roleIds = oneUser.getRoleid();
				String[] roleIdArrays = roleIds.split(",");
				List<String> roleList = Arrays.asList(roleIdArrays);
				String agentRoleId = String.valueOf(roleMapper.getIdByName(SystemConstans.A_ROLENAME));
				String newRoleId = "";
				int status = 3;
				if (roleList.size() > 1) {
					List<String> newRoleIdList = roleList.stream().filter(role -> !role.equals(agentRoleId))
							.collect(Collectors.toList());
					newRoleId = newRoleIdList.stream().collect(Collectors.joining(","));
					status = 1;
				} else {
					newRoleId = agentRoleId;
				}
				oneUser.setRoleid(newRoleId);
				oneUser.setUpdatetime(new Date());
				oneUser.setUpdateid(currentUser.getId());
				oneUser.setStatus(status);
				oneUser.setAgentId(null);
				Integer agentUserUpdate = userMapper.updateById(oneUser);
				if (agentUserUpdate < 1) {
					throw new AppCheckException("agent.editAgentInfoError.code", "agent.editAgentInfoError.message");
				}
				// 删除账号重新登录
				String account = oneUser.getAccount();
				String key = SystemConstans.USER_SESSION_CHANGE.replaceAll("\\{0\\}", account);
				keyValueDAO.set(key, SystemConstans.USER_ACOUNT_STATUS_1, 0L);

			});
		}
	}

	public void deleteAgentUser(Integer id) {

		ShiroUser currentUser = ShiroKit.getUser();
		User agentUser = userMapper.selectById(id);
		Optional.ofNullable(agentUser)
		.orElseThrow(
				() -> new AppCheckException("agent.searchUserError.code", "agent.searchUserError.message"));
		// 查询要删除的用户
		if (!agentUser.getStatus().equals(1)) {
			throw new AppCheckException("staff.userNotExistError.code", "staff.userNotExistError.message", "");
		}
		agentUser.setStatus(3);
		agentUser.setUpdateid(currentUser.getId());
		agentUser.setUpdatetime(new Date());
		agentUser.setAgentId(null);
		Integer agentUserUpdate = userMapper.updateById(agentUser);
		if (agentUserUpdate < 1) {
			throw new AppCheckException("agent.deleteAgentUserError.code", "agent.deleteAgentUserError.message");
		}
	}

	public Page<AgentUserVo> agentUserList(Page<AgentUserVo> page, QueryAgentInfo pageQuery) {

		ShiroUser currentUser = ShiroKit.getUser();
		User user = userMapper.selectById(currentUser.getId());
		pageQuery.setAgentId(user.getAgentId());
		List<AgentUserVo> searchResult = userMapper.searchAgentUserList(page, pageQuery.getSearch());
		searchResult.forEach((agentUserVo) -> {
			List<String> roleIds = Arrays.asList(agentUserVo.getRoleName().split(","));
			roleIds.forEach(roleId -> {
				int agentUserRoleId = roleMapper.getIdByName(SystemConstans.AU_ROLENAME);
				if (roleId.equals(String.valueOf(agentUserRoleId))) {
					agentUserVo.setRoleName(SystemConstans.AU_ROLENAME);
					// 0 ==> 可以删除
					agentUserVo.setIsDeleteStatus(0);
				}
				int agentRoleId = roleMapper.getIdByName(SystemConstans.A_ROLENAME);
				if (roleId.equals(String.valueOf(agentRoleId))) {
					agentUserVo.setRoleName(SystemConstans.A_ROLENAME);
					// 1 ==> 不可以删除
					agentUserVo.setIsDeleteStatus(1);
				}
			});
		});
		page.setRecords(searchResult);
		return page;
	}

	public void addAgentUser(AddAgentUser addAgentUser) {

		ShiroUser currentUser = ShiroKit.getUser();

		// 校验密码是否包含中文字符
		String staffPasswd = addAgentUser.getLoginPasswd();
		for (int i = 0; i < staffPasswd.length(); i++) {
			if (StringUtil.isChinese(staffPasswd.charAt(i))) {
				throw new AppCheckException("agent.passwdContainChinese.code", "agent.passwdContainChinese.message");
			}
		}
		// 校验当前用户是否被删除
		User user = userMapper.selectById(currentUser.getId());
		if (1 != user.getStatus()) {
			throw new AppCheckException("staff.staffUserHaveDelete.code", "staff.staffUserHaveDelete.message");
		}
		int auRoleId = roleMapper.getIdByName(SystemConstans.AU_ROLENAME);
		Map<String, Object> map = new HashMap<>();
		map.put("account", addAgentUser.getContactTel());
		List<User> agentUserList = userMapper.selectByMap(map);
		if (null != agentUserList && agentUserList.size() > 0) {
			agentUserList.forEach(agentUser -> {
				if (1 == agentUser.getStatus()) {
					String agentRoleIds = agentUser.getRoleid();
					List<String> agentRoleIdList = Arrays.asList(agentRoleIds.split(","));
					agentRoleIdList.forEach(agentRoleId -> {
						// 校验角色（老师）
							int tRoleId = roleMapper.getIdByName(SystemConstans.T_ROLENAME);
							if (String.valueOf(tRoleId).equals(agentRoleId)) {
								throw new AppCheckException("staff.staffUserExistError.code",
										"staff.staffUserExistError.message");
							}
							// 校验角色（园长）
							int kRoleId = roleMapper.getIdByName(SystemConstans.K_ROLENAME);
							if (String.valueOf(kRoleId).equals(agentRoleId)) {
								throw new AppCheckException("staff.staffUserExistError.code",
										"staff.staffUserExistError.message");
							}
							// 校验角色（员工管理员）
							int pRoleId = roleMapper.getIdByName(SystemConstans.P_ROLNAME);
							if (String.valueOf(pRoleId).equals(agentRoleId)) {
								throw new AppCheckException("staff.staffUserExistError.code",
										"staff.staffUserExistError.message");
							}
							// 校验橘色（代理商管理员）
							int aRoleId = roleMapper.getIdByName(SystemConstans.A_ROLENAME);
							if (String.valueOf(aRoleId).equals(agentRoleId)) {
								throw new AppCheckException("staff.staffUserExistError.code",
										"staff.staffUserExistError.message");
							}
							// 校验角色（代理商员工）
							if (String.valueOf(auRoleId).equals(agentRoleId)) {
								throw new AppCheckException("staff.staffUserExistError.code",
										"staff.staffUserExistError.message");
							}
						});
				} else {
					agentUser.setName(addAgentUser.getContactName());
					agentUser.setPhone(addAgentUser.getContactTel());
					agentUser.setAccount(addAgentUser.getContactTel());
					agentUser.setSalt(ShiroKit.getRandomSalt(5));
					agentUser.setPassword(ShiroKit.md5(addAgentUser.getLoginPasswd(), agentUser.getSalt()));
					agentUser.setStatus(1);
					agentUser.setCreatetime(new Date());
					agentUser.setCreateid(currentUser.getId());
					agentUser.setAgentId(user.getAgentId());
					agentUser.setRoleid(String.valueOf(auRoleId));
					agentUser.setComment(addAgentUser.getRemark());
					Integer agentUserUpdate = userMapper.updateById(agentUser);
					if (agentUserUpdate < 1) {
						throw new AppCheckException("agent.addAgentUserError.code", "agent.addAgentUserError.message");
					}
				}

			});
		} else {
			User newAgentUser = new User();
			newAgentUser.setName(addAgentUser.getContactName());
			newAgentUser.setPhone(addAgentUser.getContactTel());
			newAgentUser.setAccount(addAgentUser.getContactTel());
			newAgentUser.setStatus(1);
			newAgentUser.setCreatetime(new Date());
			int agentRoleId = roleMapper.getIdByName(SystemConstans.AU_ROLENAME);
			newAgentUser.setRoleid(String.valueOf(agentRoleId));
			newAgentUser.setCreateid(currentUser.getId());
			newAgentUser.setAgentId(user.getAgentId());
			newAgentUser.setSalt(ShiroKit.getRandomSalt(5));
			newAgentUser.setPassword(ShiroKit.md5(addAgentUser.getLoginPasswd(), newAgentUser.getSalt()));
			newAgentUser.setComment(addAgentUser.getRemark());
			newAgentUser.setDeptid(SystemConstans.DEPT_CUSTOMER_INT);
			Integer newAgentUserUpdate = userMapper.insert(newAgentUser);
			if (newAgentUserUpdate < 1) {
				throw new AppCheckException("agent.addAgentUserError.code", "agent.addAgentUserError.message");
			}
		}
	}

	public List<AgentNamesVo> getAgentNames(QueryAgentNames queryAgentNames) {

		ShiroUser currentUser = ShiroKit.getUser();

		User user = userMapper.selectById(currentUser.getId());
		String userRoleId = user.getRoleid();
		String[] userRoleIdList = userRoleId.split(",");
		List<AgentNamesVo> agentNamesVos = null;
		for (String role : userRoleIdList) {
			int staffId = roleMapper.getIdByName(SystemConstans.A_ROLENAME);
			if (String.valueOf(staffId).equals(role)) {
				Long agentId = user.getAgentId();
				TAgentInfo agentInfo = agentInfoMapper.selectById(agentId);
				agentNamesVos = agentInfoMapper.getAgentNames(agentInfo.getAgentName());
				return agentNamesVos;
			}
		}
		agentNamesVos = agentInfoMapper.getAgentNames(queryAgentNames.getName());
		return agentNamesVos;
	}

	public Long getAgentId(QueryAgentId queryAgentId) {

		Long agentId = agentInfoMapper.getAgentId(queryAgentId.getAgentName());
		return agentId;
	}

	public AgentStatisticalDataVo getStatisticalData(Date start, Date end, Integer flag) {

		int agentCount = agentInfoMapper.selectCount(new EntityWrapper<TAgentInfo>().eq("is_delete", 0));
		int schoolCount = schoolInfoMapper.selectCount(new EntityWrapper<SchoolInfo>().eq("is_delete", 0));
		AgentStatisticalDataVo agentStatisticalDataVo = new AgentStatisticalDataVo();

		if (flag == SystemConstans.YES) {
			ShiroUser currentUser = ShiroKit.getUser();
			User user = userMapper.selectById(currentUser.getId());
			if (!user.getStatus().equals(SystemConstans.YES)) {
				throw new AppCheckException("school.user.notActive.code", "school.user.notActive.message");
			}
			if (user.getAgentId() == null) {
				throw new AppCheckException("agent.searchUserError.code", "agent.searchUserError.message");
			}
			Map<String, Object> param = new HashMap<String, Object>();
			if (start == null || end == null) {
				end = new Date();
				start = DateUtil.addDaysToDate(end, -30);
				List<Date> formateDate = DateUtil.formateDate(start, end);
				start = formateDate.get(0);
				end = formateDate.get(1);
			}
			if (end != null) {
				end = DateUtil.formate(end, false);
			}
			param.put("start", start);
			param.put("end", end);
			param.put("agentId", user.getAgentId());
			AgentStatisticalDataVo count = billDetailMapper.findCountByParam(param);
			agentStatisticalDataVo.setFlow(count.getFlow());
			agentStatisticalDataVo.setAliFlow(count.getAliFlow());
			agentStatisticalDataVo.setWeixinFlow(count.getWeixinFlow());
			agentStatisticalDataVo.setUndergroundFlow(count.getUndergroundFlow());
		} else if (flag == SystemConstans.TWO) {
			Map<String, Object> param = new HashMap<String, Object>();
			if (start == null || end == null) {
				end = new Date();
				start = DateUtil.addDaysToDate(end, -30);
				List<Date> formateDate = DateUtil.formateDate(start, end);
				start = formateDate.get(0);
				end = formateDate.get(1);
			}
			if (end != null) {
				end = DateUtil.formate(end, false);
			}
			param.put("start", start);
			param.put("end", end);
			AgentStatisticalDataVo count = billDetailMapper.findCountByParam(param);
			agentStatisticalDataVo.setFlow(count.getFlow());
			agentStatisticalDataVo.setAliFlow(count.getAliFlow());
			agentStatisticalDataVo.setWeixinFlow(count.getWeixinFlow());
			agentStatisticalDataVo.setUndergroundFlow(count.getUndergroundFlow());

		} else {
			BigDecimal allFlow = billDetailMapper.getTotalCount();
			agentStatisticalDataVo.setAgentCount(agentCount);
			agentStatisticalDataVo.setFlow(allFlow);
			agentStatisticalDataVo.setSchoolCount(schoolCount);
		}

		return agentStatisticalDataVo;
	}

	public List<HotAgentVo> getHotAgentData(Date startTime, Date endTime) {

		List<HotAgentVo> hotAgentVos = agentInfoMapper
				.getHotAgentData(startTime, DateUtil.addDaysToDate(endTime, 1));
		hotAgentVos.forEach(hotAgentVo -> {
			if (null == hotAgentVo.getChargeAmount()) {
				hotAgentVo.setChargeAmount(new BigDecimal("0"));
			}
		});
		return hotAgentVos;
	}

	public AgentCountDataVo getAgentCountData(QueryAgentCountData agentCountData) {

		AgentCountDataVo agentCountDataVo = new AgentCountDataVo();
		int totalSchoolCount = agentInfoMapper.getAgentTotalSchoolCount(agentCountData.getUserId());
		BigDecimal totalAgentFlow = agentInfoMapper.getAgentTotalFlow(agentCountData.getUserId());
		agentCountDataVo.setSchoolTotalCount(totalSchoolCount);
		if (null == totalAgentFlow) {
			agentCountDataVo.setAgentTotalFlow(new BigDecimal("0"));
		} else {
			agentCountDataVo.setAgentTotalFlow(totalAgentFlow);
		}
		return agentCountDataVo;
	}
}
